package com.xuan.xwaterfall.loader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.app.Activity;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

import com.xuan.xwaterfall.util.EnvironmentUtil;
import com.xuan.xwaterfall.util.ExecutorUtil;
import com.xuan.xwaterfall.util.FileUtil;
import com.xuan.xwaterfall.util.ImageUtil;
import com.xuan.xwaterfall.util.ShareValue;

public class ImageLoader {
	private static String path = EnvironmentUtil.getRootFilePath() + "xuan/";
	private static Map<String, Bitmap> map = new ConcurrentHashMap<String, Bitmap>(50);

	public static void deleteBitmap(String url){
		map.remove(url);
	}
	
	public static Bitmap getBitmap(String url) {
		return map.get(url);
	}

	public static void loadImg(String url, ImageView iv) {
		PhotosLoader pl = new PhotosLoader(url, iv);
		ExecutorUtil.getFixedExecutorService().submit(pl);
	}

	static class PhotosLoader implements Runnable {
		String url;
		ImageView iv;

		public PhotosLoader(String url, ImageView iv) {
			this.url = url;
			this.iv = iv;
		}

		@Override
		public void run() {
			Bitmap bitmap = map.get(url);
			if (bitmap == null) {
				FileUtil.createDirectory(path);
				File file = new File(path + url.hashCode());
				if (file.exists()) {

				} else {
					URL imageUrl;
					try {
						imageUrl = new URL(url);
						HttpURLConnection connection = (HttpURLConnection) imageUrl
								.openConnection();
						connection.setConnectTimeout(3000);
						connection.setReadTimeout(30000);
						connection.setInstanceFollowRedirects(true);
						if (connection.getResponseCode() != 200)
							return;
						InputStream is = connection.getInputStream();
						OutputStream os = new FileOutputStream(file);
						CopyStream(is, os);
						os.close();
						connection.disconnect();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				// 将图片按宽度缩放到指定大小,这个根据自己的应用设置吧
				bitmap = ImageUtil.decodeFile(file, ShareValue.imgWidth);
				map.put(url, bitmap);
			}
			// // 更新的操放在UI线程中
			Activity activity = (Activity) iv.getContext();
			activity.runOnUiThread(new BitmapDisplayer(bitmap, iv));
		}

	}

	/**
	 * 用于在UI线程中更新界面
	 */
	static class BitmapDisplayer implements Runnable {

		Bitmap bitmap;
		ImageView iv;

		public BitmapDisplayer(Bitmap bitmap, ImageView iv) {
			this.bitmap = bitmap;
			this.iv = iv;
		}

		@Override
		public void run() {
			if (bitmap != null) {
				iv.setImageBitmap(bitmap);
			}
		}
	}

	/**
	 * 将输入流写入输入流
	 * 
	 * @param is
	 * @param os
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1) {
					break;
				}
				os.write(bytes, 0, count);
			}
		} catch (Exception e) {
			Log.e("CopyStream", "CopyStream catch Exception...");
		}
	}
}
